﻿<?php
#============================
#	daily 日报管理
#============================
!defined('IN_SYSTEM') && exit('Access denied');

class dailyControlPage extends commonControlPage 
{
	/*[获得近三天没提交日报的日子]*/
	private function GetDailyDate($uid)
	{
		$count = 3;
		
		//最后一次提交的日期
		$predateline = $_ENV['db']->fetchCol("SELECT dateline FROM  daily where uid='{$uid}' and audit_state!='0' order by dateline desc LIMIT 1 ");
		if(!$predateline)
		{
			$predateline = date('Ymd');
		}
		
		for($i=$count;$i>0;$i--)
		{
			$init = date('Ymd',time() - $i*24*60*60);
			$predateline = $_ENV['db']->fetchCol("SELECT dateline FROM  daily where uid='{$uid}' and audit_state!='0' order by dateline desc LIMIT 1 ");
			if($predateline>$init)
			{
				continue;	
			}
			$dateline = $_ENV['db']->fetchCol("SELECT dateline FROM  daily where `dateline` ='{$init}' and uid='{$uid}' and audit_state!='0' ");
			if(!$dateline)
			{
				return $init;
			}
		}
		return false;
	}
	
	//填写日报和处理
    public function postModule() 
	{  
		if (AJAX && $_GET['opt']=='GetCustomer') 
		{ 
       		$users = $_ENV['db']->fetchAll("SELECT * FROM customer WHERE customer_name LIKE '%{$_REQUEST['q']}%' and state='1' ");
            exit( json_encode($users));
		}
	
		if (AJAX && $_GET['opt']=='GetUser') 
		{ 
       		$users = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m");
            exit( json_encode($users) );
        }
	
		if(POST && AJAX && $_POST['type']=='pass')
		{ //跳过
			$postDate = $_POST['dateline'];
			$posttime = mktime(0, 0, 0, substr($postDate,4,2), substr($postDate,6,2), substr($postDate,0,4));
			$postDate = date("Y-m-d",$posttime);
			
			$current_day = date('Y-m-d');
			if($postDate>=$current_day)
			{
				$this->outputJson(0,'不能跳过当前日期');
			}
			else
			{
				$this->outputJson(1,date('Ymd',$posttime + 1*24*60*60));
			}
		}
	
		// 获取今天的日报日期
		$current_day = $this->GetDailyDate($this->user['uid']);
		if(!$current_day)
		{
			$current_day = date('Ymd');
		}
		$daily = dailyEntity::GetTodayDaily($current_day,$this->user['uid']);
        // 检测今天的日报是否已经提交
        if ($daily && $daily['audit_state']!=0) 
		{
            $this->showMessage('您今天的日报已经提交过了',AJAX?'0':'back');
        }
		$act = $daily ?'edit':'add';
		$daily_detail = @json_decode($daily['detail'],1);

		// 初始化项目阶段、工作结果和项目
		$pw['project_phase'] = explode("\n",$_ENV['config']['project_phase']);
		$pw['work_result']   = explode("\n",$_ENV['config']['work_result']);	
		$dailyitems          = explode("\n",$_ENV['config']['daily_item']);
		foreach((array)$dailyitems as $ivalue){
			list($dk,$dv) = explode('-',$ivalue);
			$pw['daily_item'][$dk] = $dv;
		}
		$this->view->daily_item    = BindComboxForKey('daily_item','daily_item',$pw['daily_item']);
		if($act=='add')
		{  //添加
			$this->view->project_phase = BindCombox('project_phase[]','project_phase',$pw['project_phase']);
			$this->view->work_result   = BindCombox('work_result[]','work_result',$pw['work_result']);
			
		}
		else
		{  //修改
			foreach((array)$daily_detail as $rkey=>$rvalue)
			{
				$daily_detail[$rkey]['project_phase'] = BindCombox('project_phase[]','project_phase',$pw['project_phase'],$rvalue['project_phase']);
				$daily_detail[$rkey]['work_result']   = BindCombox('work_result[]','work_result',$pw['work_result'],$rvalue['work_result'] );
				$daily_detail[$rkey]['itmes'] = array();
				foreach($rvalue as $rrkey => $rrvalue)
				{
					if($rrkey=='other_mark' || $rrkey=='other_subtotal' || $rrkey=='mark' ||$rrkey=='result_mark' || $rrkey=='work_mark')
					{  //备注、对应费用明细、其他小计可以为空
						continue;
					}
					 if ('mark' == substr($rrkey,-4)) 
					{
						$temp =explode("_",$rrkey);
                 		$daily_detail[$rkey]['itmes'][$temp[0]]['mark'] = htmlspecialchars($rrvalue);
						$daily_detail[$rkey]['itmes'][$temp[0]]['title'] = htmlspecialchars($pw['daily_item'][$temp[0]]);
               		}
					else if ('subtotal' == substr($rrkey,-8)) 
					{ 
						$temp =explode("_",$rrkey);
                 		$daily_detail[$rkey]['itmes'][$temp[0]]['subtotal'] = htmlspecialchars($rrvalue);
						$daily_detail[$rkey]['itmes'][$temp[0]]['title'] = htmlspecialchars($pw['daily_item'][$temp[0]]);
                 	}
				}
			}
		}
		if (POST && AJAX) 
		{  //日报信息添加Ajax处理
			
			//初始化项数据
			$detail =  dailyEntity::InitItemDetail();
            $data = array();
            foreach ($detail as $k=>$v) 
			{ //解析POST过来的数据
                $data[$k] = $_POST[$k];
            }
			/*封装和格式化用户提交的数据*/
			$saved = $this->PackageData($data,$pw,$detail);
			unset($data);
            $sarr = array();
            $sarr['detail'] = addslashes(json_encode($saved));
			$logContent = '';  //日志内容
			$thisID     = '';  //日报ID
            switch($_POST['opt']) 
			{
                case 'submit': //提交
                    $next_uid = $_POST['next_uid'];
					if (!class_permission::ValidateNodeByUser($_ENV['config']['daily_audit_nodes'][0],$next_uid)) 
					{
						$this->outputJson(0,'指定的操作员无权限');
					}
                    $sarr['co_member_id'] = $next_uid;
                    $sarr['audit_state']  = '1';              //单据状态未审核
					$logContent = '提交日报';
               		break;
                case 'save':  //保存
                    $sarr['audit_state']  = '0';              //单据状态未提交
					$logContent = '保存日报';
                	break;
                default:
                    $this->outputJson(0,'未知的操作');
                	break;
            }
			$sarr['uid']      = $this->user['uid'];       
			$sarr['username'] = $this->user['username'];  
			$sarr['nickname'] = $this->user['nickname'];
			$sarr['dateline'] = $_POST['dateline']; //$current_day;
			$sarr['created_time'] = $_ENV['time'];
            if (!$daily) 
			{  //今天无日报添加
			   $thisID = InsertTable("daily",$sarr);
            }
			else 
			{  //今天日报保存未发布
				UpdateTable("daily",$sarr,array("daily_id"=>$daily['daily_id']));
				$thisID = $daily['daily_id'];
            }
			logEntity::AddDailyHistory($thisID,$this->user,$logContent);
			$this->outputJson(1,'操作完成');
		}
        $this->view->addScript("autocomplete");
		/*[下级操作人]*/
		$users = class_permission::GetUsersByNodeID($_ENV['config']['daily_audit_nodes'][0]);
		if($users){
			$this->view->users =  BindComboxs('next_uid','next_uid',$users,'uid','nickname');
		}
		$this->view->current_day    = $current_day;
        $this->view->daily_desc    = $daily_detail;
		$this->view->act = $act;
        $this->showMainPage('admincp/daily_post');
    }
	/*封装数据*/
	private function PackageData($data,$pw,$detail)
	{
		$saved = array();
        foreach ($data as $bkey=>$item) 
		{ 
        	foreach ((array)$item as $k=>$v) 
			{  //$saved[表单索引][键] = 值
            	$saved[$k][$bkey] = $v;
            }
         }
		 $loop_index = 1;
         foreach ($saved as $fkey=>$item) 
		 {   //遍历表单组里数据
             foreach ((array)$item as $key=>$val) 
			 {
				if($key=='other_mark' || $key=='other_subtotal' || $key=='mark' )
				{  //备注、对应费用明细、其他小计可以为空
					continue;
				}
				if($key=='work_object')
				{  //工作对象必须是客户
					$users = $_ENV['db']->fetchAll("SELECT * FROM customer WHERE customer_name = '{$val}'");
					if(!$users )
					{
						$this->outputJson(0,"工作对象客户{$val}不存在");
					}
				}
                $cur_input = "第  [ {$loop_index} ]  个的".$detail[$key];
                if (empty($val)) 
				{ //提交结果都不能为空
                 	$this->outputJson(0,"{$cur_input}不能为空");
                }
                if (('project_phase'==$key || 'work_result'==$key) && !in_array($val,$pw[$key])) 
				{ //项目阶段和工作结果必须时系统维护的
                     $this->outputJson(0,"{$cur_input}错误");
                } 
				else if ('mark' == substr($key,-4)) 
				{
                 	$saved[$fkey][$key] = htmlspecialchars($val);
               }
				else if ('subtotal' == substr($key,-8) && !preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$val)) 
				{  //小计格式必须是浮点
                    $this->outputJson(0,"{$cur_input}数据格式不正确");
                 }
             }
             $loop_index ++;
         }
		 return $saved;
	}
	
	// 日报总览
	public function listModule() 
	{
		if (preg_match('/[0-9]+/',$_GET['daily_id'])) 
		{
			$daily = $_ENV['db']->fetch("SELECT * FROM `daily` WHERE `daily_id` = '".(int)$_GET['daily_id']."'");
            
			$daily['audit_statename'] = $this->GetOrderStatus($daily['audit_state'] );
			$daily['detail'] = @json_decode($daily['detail'],1);
            if ($daily['audit_state']>2) 
			{
                $this->view->print = 1;
            }
			$this->view->addScript('LodopFuncs');
			$this->view->isMy = "1";
			$this->view->year = date('Y');
			$this->view->moth = date('m');
			$this->view->today = date('d');
			$details = array();
			$details = array('other_subtotal'=>'其他');
			foreach (explode("\n",$_ENV['config']['daily_item']) as $v) 
			{ //遍历自定义项目加入$details
				list($dk,$dv) = explode("-",$v);
             	$details[$dk.'_subtotal'] = $dv;
			}
			$items = array();
			$items['day'] = array();
			$items['moth'] = array();
			$items['mark'] = array();
			$items['subtotal'] = array();
			$items['thisname'] = array();
			$items['des'] = array();
			$des = '';
			$totalAmount = 0;
			foreach((array)$daily['detail'] as $inkey =>$invalue)
			{
				foreach ((array)$invalue as $key=>$val) 
				{
					if($key=='mark')
					{
						 $des = htmlspecialchars($val);
						 continue;
					}
					if("result_mark"==$key  ||  'work_mark'==$key )
					{   //排除非自定义项
						continue;	
					}
					if ('mark' == substr($key,-4)) 
					{ 
						$items['mark'][] = htmlspecialchars($val);
						$items['moth'][] = date('m',$daily['created_time']);
						$items['day'][]  = date('d',$daily['created_time']);
					}
					else if ('subtotal' == substr($key,-8)) 
					{  
						$items['subtotal'][] = htmlspecialchars($val);
						$items['thisname'][] = $details[$key];
						$totalAmount = $totalAmount + floatval($val);
					}
				}
			}
			$this->view->totals = toCNcap($totalAmount);
			$this->view->items = $items;
			$this->view->des = $des;
			

				$results = array();
				$allTotal = 0;
				foreach((array)$daily['detail']  as $rkey=>$rvalue)
				{
					$thisTotal = 0;
					foreach((array)$rvalue as $inkey =>$invalue)
					{
						if ('subtotal' == substr($inkey,-8)) 
						{  
							$thisTotal  =  floatval($thisTotal)  + floatval($invalue);
						}
					}
					$rvalue['total'] += $thisTotal;
					$allTotal += $thisTotal;
					$results[] = $rvalue;
				}
				$this->view->total  = $allTotal ;
				$this->view->results = $results ;
			
			//封装后台项目，便于前台展示
			$this->PackageItem($daily);
			
			/*模板变量赋值*/
            $this->view->daily = $daily;
			$this->view->logs  = logEntity::GetDailyHistory($_GET['daily_id']);
            $this->showMainPage('admincp/daily_desc');
		} 
		else 
		{
			$this->GetListAudited($this->user['uid']);
			$this->showMainPage('admincp/daily_list');
		}
	}
	
	//返回审核过的所有日报列表
	private function GetListAudited($uid)
	{
		$where = '1';
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		// marge get
		if (!empty($_GET['searchtype']) && $_GET['keyword']) 
		{
			switch ($_GET['searchtype']) {
				case '1':break;
			}
		}
        if ($uid && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) {  //超级管理员能够展示所有日报
            $where .= ' and ( `audit1_uid` ='.$uid.' or  `audit2_uid` ='.$uid.' or `audit3_uid` ='.$uid.' ) '; //暂时审核过或核销的日报
        }
		$sql = "SELECT count(daily_id) as total FROM `daily` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.http_build_query($_GET),'TPT');
		$this->view->pager = $pager->output();
		$this->view->daily_list = $_ENV['db']->fetchAll("SELECT * FROM `daily` WHERE {$where} order by daily_id desc LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
	}

	//我的日报
    public function myModule() 
	{
        if (!empty($_GET['daily_id'])) 
		{  //日报详情
            $daily = $_ENV['db']->fetch("SELECT * FROM `daily` WHERE `daily_id` = '".(int)$_GET['daily_id']."'");
            
			$daily['audit_statename'] = $this->GetOrderStatus($daily['audit_state'] );
			$daily['detail'] = @json_decode($daily['detail'],1);
            if ($daily['audit_state']>2) 
			{
                $this->view->print = 1;
            }
			$this->view->addScript('LodopFuncs');
			$this->view->isMy = "1";
			$this->view->year = date('Y');
			$this->view->moth = date('m');
			$this->view->today = date('d');
			$details = array();
			$details = array('other_subtotal'=>'其他');
			foreach (explode("\n",$_ENV['config']['daily_item']) as $v) 
			{ //遍历自定义项目加入$details
				list($dk,$dv) = explode("-",$v);
             	$details[$dk.'_subtotal'] = $dv;
			}
			$items = array();
			$items['day'] = array();
			$items['moth'] = array();
			$items['mark'] = array();
			$items['subtotal'] = array();
			$items['thisname'] = array();
			$items['des'] = array();
			$des = '';
			$totalAmount = 0;
			foreach((array)$daily['detail'] as $inkey =>$invalue)
			{
				foreach ((array)$invalue as $key=>$val) 
				{
					if($key=='mark')
					{
						 $des = htmlspecialchars($val);
						 continue;
					}
					if("result_mark"==$key  ||  'work_mark'==$key )
					{   //排除非自定义项
						continue;	
					}
					if ('mark' == substr($key,-4)) 
					{ 
						$items['mark'][] = htmlspecialchars($val);
						$items['moth'][] = date('m',$daily['created_time']);
						$items['day'][]  = date('d',$daily['created_time']);
					}
					else if ('subtotal' == substr($key,-8)) 
					{  
						$items['subtotal'][] = htmlspecialchars($val);
						$items['thisname'][] = $details[$key];
						$totalAmount = $totalAmount + floatval($val);
					}
				}
			}
			$this->view->totals = toCNcap($totalAmount);
			$this->view->items = $items;
			$this->view->des = $des;
			

				$results = array();
				$allTotal = 0;
				foreach((array)$daily['detail']  as $rkey=>$rvalue)
				{
					$thisTotal = 0;
					foreach((array)$rvalue as $inkey =>$invalue)
					{
						if ('subtotal' == substr($inkey,-8)) 
						{  
							$thisTotal  =  floatval($thisTotal)  + floatval($invalue);
						}
					}
					$rvalue['total'] += $thisTotal;
					$allTotal += $thisTotal;
					$results[] = $rvalue;
				}
				$this->view->total  = $allTotal ;
				$this->view->results = $results ;
			
			
			
			//封装后台项目，便于前台展示
			$this->PackageItem($daily);
			
			/*模板变量赋值*/
            $this->view->daily = $daily;
			$this->view->logs  = logEntity::GetDailyHistory($_GET['daily_id']);
            $this->showMainPage('admincp/daily_desc');
        } 
		else 
		{  //日报列表
		   //日期选择控件JS
			$this->view->addScript('rili');
			$page = (int)$_GET['page_no'];
			$_GET['page_no'] = 'TPT';
				
			$type = $_GET['type']? $_GET['type']:'m';
			
			if($type=='m')
			{  //我的欠款记录
				$where = ' 1 and uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->maction = ' class="active" ';
			}
			else if($type=='s')
			{
				$where = '1 and audit1_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->saction = ' class="active" ';
			}
			else if($type=='f')
			{
				$where = '1 and audit2_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->faction = ' class="active" ';
			}
			else if($type=='x')
			{
				$where = '1 and audit3_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->xaction = ' class="active" ';
			}
			$list =  $this->PrePage('daily','daily_id',$where,$page,'daily_id desc');
			foreach((array)$list as $key=>$value)
			{
				$list[$key]['audit_state'] = $this->GetOrderStatus($value['audit_state']);
			}
			$this->view->daily_list = $list;
			$this->view->type = $type;
            $this->showMainPage('admincp/daily_mylist');
        }
    }

	//获得请假单状态
	private function GetOrderStatus($code)
	{
		switch($code)
		{
			case '0':  return '<span style="color:red; font-size:14px;">未提交</span>';  break;
			case '1':  return '<span style="color:blue; font-size:14px;">未审批</span>';  break;
			case '2':  return '<span style="color:blue; font-size:14px;">未复审</span>';  break;
			case '3':  return '<span style="color:blue; font-size:14px;">未核销</span>';  break;
			case '4':  return '<span style="color:green; font-size:14px;">批准</span>';  break;
		}
		return '未审批';
	}

	//魔术方法 审核流程
    public function __call($func,$args) 
	{
	    if (substr($func,0,5) == 'audit' && substr($func,5,1) > 0 && substr($func,5,1) < 4) 
		{   //限定三级审核
            $step = substr($func,5,1); //当前进行的审核级别
			if (preg_match('/[0-9]+/',$_GET['daily_id'])) 
			{
				$daily = $_ENV['db']->fetch("SELECT * FROM `daily` WHERE `daily_id` = '{$_GET['daily_id']}'");
				if (!$daily) $this->showMessage('指定的日志不存在',AJAX?0:'back');
				$daily['audit_statename'] = $this->GetOrderStatus($daily['audit_state'] );
				$daily['detail'] = @json_decode($daily['detail'],1);
				
				$results = array();
				$allTotal = 0;
				foreach((array)$daily['detail']  as $rkey=>$rvalue)
				{
					$thisTotal = 0;
					foreach((array)$rvalue as $inkey =>$invalue)
					{
						if ('subtotal' == substr($inkey,-8)) 
						{  
							$thisTotal  =  floatval($thisTotal)  + floatval($invalue);
						}
					}
					$rvalue['total'] += $thisTotal;
					$allTotal += $thisTotal;
					$results[] = $rvalue;
				}
				$this->view->total  = $allTotal ;
				$this->view->results = $results ;
				//print_r($result);
				$node_id = $_ENV['config']['daily_audit_nodes'][$step];
				if (POST && AJAX) 
				{   //日报信息审核Ajax处理
					$param = array();
					$param['audit_state'] = $step+1;
					$next_uid = (int)$_POST['next_uid'];
					$param['co_member_id'] = $next_uid;
					$logContent = '';   //日志内容
					switch($step) 
					{
						case '1':  //一审  要打分和填评价
							$score = $_POST['score'];
							$p = htmlspecialchars($_POST['p']);
							if (!preg_match('/[0-9]+/',$score)) {
								$this->outputJson(0,'请正确填写评分');
							}
							if (!$p) {
								$this->outputJson(0,'请填写评价');
							}
							$param['score'] = $score;
							$param['app'] = $p;
							$param['audit1_uid']      = $this->user['uid'];
							$param['audit1_username'] = $this->user['username'];
							$param['audit1_dateline'] = $_ENV['time'];
							$logContent = '审批日报';
						break;
						case '2':  //二审
							//$score = $_POST['score'];
							//$p = htmlspecialchars($_POST['p']);
							//if (!preg_match('/[0-9]+/',$score)) {
							//	$this->outputJson(0,'请正确填写评分');
							//}
							//if (!$p) {
							//	$this->outputJson(0,'请填写评价');
							//}
							//$param['score2'] = $score;
							//$param['app2'] = $p;
							$param['audit2_uid'] = $this->user['uid'];
							$param['audit2_username'] = $this->user['username'];
							$param['audit2_dateline'] = $_ENV['time'];
							$logContent = '二级审批日报';
						break;
						case '3':   //财务核销
							$param['audit3_uid'] = $this->user['uid'];
							$param['audit3_username'] = $this->user['username'];
							$param['audit3_dateline'] = $_ENV['time'];
							$logContent = '财务销核日报';
							//隐含bug,费用项目可维护对此有影响
							//$lufei = empty($daily['detail'][0]['lufei_subtotal'])?"0":$daily['detail'][0]['lufei_subtotal'];  //路费费用
//							$zhusu = empty($daily['detail'][0]['zhusu_subtotal'])?"0":$daily['detail'][0]['zhusu_subtotal'];  //住宿费用
//							$_ENV['db']->runSql("UPDATE `admincp_member_detail` ".$this->buildSql(array(
//								'price_traffic' => 'price_traffic+'.$lufei,
//								'price_live' => 'price_live+'.$zhusu,
//								'price_other' => 'price_other+'.$daily['detail'][0]['other_subtotal'],
//								'price_total' => 'price_total+'.($lufei+$zhusu+$daily['detail'][0]['other_subtotal'])
//							))." WHERE `uid` = '{$daily['uid']}'");
						break;
					}
					# 检测指定的下级用户是否有权限
					if ($step!=3) 
					{   //财务核销不检测权限？
						$cr = $_ENV['db']->fetchCol("SELECT node_id FROM admincp_member_perm WHERE node_id = '{$node_id}' AND uid = '{$next_uid}'");
						if (!$cr) $this->outputJson(0,'指定的下级操作员没有足够的权限');
					}
					$_ENV['db']->runSql("UPDATE `daily` ".$this->buildSql($param)." WHERE `daily_id` = '{$_GET['daily_id']}'");
					
					logEntity::AddDailyHistory($_GET['daily_id'],$this->user,$logContent);
					$this->outputJson(1,'操作成功');
				}

				// 获取下级操作员列表
				$next_user_list = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$node_id}'");
				switch ($step) {
					case '1':
						$operation = '<input type="submit" value="审核通过，转二级审核"/>';
					break;

					case '2':
						$operation = '<input type="submit" value="审核通过，转核销"/>';
					break;

					case '3':
						$operation = '<input type="submit" value="核销完毕，提交更改"/>';
					break;
				}
				//封装后台项目，便于前台展示
				$this->PackageItem($daily);
				
				$this->view->operation = $operation;
				$this->view->next_user_list = $next_user_list;
				$this->view->step = $step;
                $this->view->daily = $daily;
				
				$this->view->logs  = logEntity::GetDailyHistory($_GET['daily_id']);
				$this->showMainPage('admincp/daily_desc');
			} 
			else 
			{
				$this->doDailyList($step,$this->user['uid']);
			    $this->showMainPage('admincp/daily_list');
			}
        } 
		else 
		{
            parent::__call($func,$args);
        }
    }
	
	//封装后台项目，便于前台展示
	private function PackageItem($daily)
	{
		foreach (explode("\n",$_ENV['config']['daily_item']) as $v) 
		{ //遍历自定义项目加入$detail
			list($dk,$dv) = explode("-",$v);
			$detail[$dk.'_mark'] = $dv.'明细';
			$detail[$dk.'_subtotal'] = $dv.'小计';
		}
		//封装$result 便于前台展示自定义项目
		$result = array();
		foreach($daily['detail'] as $fkey=>$item)
		{
			foreach ((array)$item as $key=>$val) 
			{
				if("result_mark"==$key || "other_mark"==$key || 'other_subtotal'==$key || 'work_mark'==$key || 'mark'==$key)
				{   //排除非自定义项
					continue;	
				}
				$name = substr($key,0,strrpos($key,'_')); 
				if ('mark' == substr($key,-4)) 
				{ 
					$result[$fkey][$name][$key] = htmlspecialchars($val);
				}
				else if ('subtotal' == substr($key,-8)) 
				{  
					$result[$fkey][$name][$key] = htmlspecialchars($val);
				}
			}
		}
		$this->view->result = $result;
		$this->view->detail = $detail;
	}
	
	public function call($method) {
		$allowed = array(
				'doDailyList'
			);
		if (in_array($method,$allowed)) {
			call_user_func(array($this,$method));
		}
	}

	//根据审核步骤显示日报列表
	private function doDailyList($audit_state='',$uid='') 
	{
		$where = '1';
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';

		// marge get
		if (!empty($_GET['searchtype']) && $_GET['keyword']) 
		{
			switch ($_GET['searchtype']) {
				case '1':break;
			}
		}
		if ($audit_state) {  //审核步骤
			$where .= ' and `audit_state` = '.$audit_state;
		}
        if ($uid && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) {  //超级管理员能够展示所有日报
            $where .= ' and `co_member_id` = '.$uid;
        }
		$sql = "SELECT count(daily_id) as total FROM `daily` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.http_build_query($_GET),'TPT');
		$this->view->pager = $pager->output();
		$this->view->daily_list = $_ENV['db']->fetchAll("SELECT * FROM `daily` WHERE {$where} order by daily_id desc LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
	}
	
	//常用费用统计报表
	public function reportModule()
	{
		//日期选择控件JS
		$this->view->addScript('rili');
        $this->view->addScript('autocomplete');
		if (AJAX && $_GET['opt']=='getuser') 
		{ 
       		$users = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m");
            exit( json_encode($users) );
        }
		if (AJAX && $_GET['opt']=='getcustomer') 
		{ 
       		$users = $_ENV['db']->fetchAll("SELECT m.customer_name,m.customer_id FROM `customer` as m");
            exit( json_encode($users) );
        }
		$where = " 1 ";
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';  
		if($_GET['start_date'] && $_GET['end_date'])
		{
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		$sel_UName = $_GET['searchUser'];       //查询人名称	
		//$sel_phase = $_GET['searchPhase'];    //项目阶段
		//$sel_Item = $_GET['searchItem'];      //选择项目
		if ($sel_UName ) 
		{   //通过用户名获得用户ID （UID）
			$sel_UID = $_ENV['db']->fetchCol("SELECT m.uid FROM `admincp_member` as m where username='". $sel_UName ."'");
        	$where .= ' and `uid` = '.$sel_UID;
       	}
		$sql = "SELECT count(daily_id) as total FROM `daily` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.http_build_query($_GET),'TPT');
		$this->view->pager = $pager->output();
		$dailys = $_ENV['db']->fetchAll("SELECT * FROM `daily` WHERE {$where} order by created_time asc,daily_id desc LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
		$result = array();
		foreach((array)$dailys as $daily)
		{
			//计算本次项目金额总计
			$dailyTotal = 0;   //此次申请金额小计
			$temp_detail = @json_decode($daily['detail'],1);
			$loop_i = 0;
			$daily["items"] = array();
			foreach ((array)$temp_detail as $key=>$val) 
			{
				$itemTotal = 0;   //本次项目阶段金额小计
				$loop_i2   = 0;
				foreach((array)$val as $inkey =>$invalue)
				{
					if ('subtotal' == substr($inkey,-8)) 
					{  
						$daily["items"][$key]['project_phase'] = $val['project_phase'];
						$daily["items"][$key][$inkey] = htmlspecialchars($invalue);
						$dailyTotal =  floatval($dailyTotal) + floatval($invalue);
						$itemTotal = floatval($itemTotal) + floatval($invalue);
					}
				}
				$daily["items"][$key]["total"] = htmlspecialchars($itemTotal);
				$loop_i2++;
			}
			$daily["total"] = $dailyTotal;
			
			if(!array_key_exists($daily['nickname'],$result))
			{
				$result[$daily['nickname']] = array(); 
			}
			$result[$daily['nickname']][$daily['dateline']] = $daily;
			//计算总金额
			$result[$daily['nickname']]["total"] = floatval($result[$daily['nickname']]["total"]) + floatval($daily["total"]);
		}
		$details = array(
					'project_phase' => '项目阶段名称',
					'other_subtotal' => '其他小计',
					'total' => '项目阶段小计',);
		foreach (explode("\n",$_ENV['config']['daily_item']) as $v) 
		{ //遍历自定义项目加入$details
          	 list($dk,$dv) = explode("-",$v);
             $details[$dk.'_subtotal'] = $dv.'小计';
		}
		$this->view->details = $details;
		
		//得到用户列表
		$user_list = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m");
        $this->view->users = $user_list;
		
		// 项目阶段
		$pw['project_phase'] = explode("\n",$_ENV['config']['project_phase']);
		$this->view->project_phase = $pw['project_phase'];
		$this->view->result = $result;
		$this->view->sel_UName = $sel_UName;
		$this->view->sel_Item = $sel_Item;
		$this->view->sel_phase = $sel_phase;
		$this->showMainPage('admincp/daily_report');
	}
	
	//验证时间格式
	private function checkDateFormat() 
	{
        $start_date = $_GET['start_date'];
        $end_date = $_GET['end_date'];
		$this->view->start_date = $start_date;   //开始时间
		$this->view->end_date = $end_date;       //结束时间
        if (!ValidateDate($start_date) || !ValidateDate($end_date)) {
            $this->showMessage('日期格式错误','back');
        }
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date." 23:59:59");
        if ($start_date > $end_date) {
            $this->showMessage('结束时间必须小于开始时间','back');
        }
        if (($end_date-$start_date) > 31536000) {
            $this->showMessage('所选日期时间段超过了1年','back');
        }	
        return array('s'=>$start_date,'e'=>$end_date);
    }
	
	/*[日报报表]*/
	public function morereportModule()
	{
		$opt = in_array($_GET['opt'],array('summary','mingxi','kehu','yuangong','huafei')) ? $_GET['opt'] : 'summary';
		//日期选择控件JS
		$this->view->addScript('rili');
        $this->view->addScript('autocomplete');
		
		$dailys    = $this->GetDailys();
		$customer  = $_GET['searchCustomer'];
		$sel_UName = $_GET['searchUser'];
		$details = array(
					'project_phase' => '项目阶段名称',
					'other_subtotal' => '其他小计',
					'total' => '项目阶段小计',);
		foreach (explode("\n",$_ENV['config']['daily_item']) as $v) 
		{ //遍历自定义项目加入$details
          	 list($dk,$dv) = explode("-",$v);
             $details[$dk.'_subtotal'] = $dv.'小计';
		}
		
		$result = array();
		switch($opt )
		{
			case 'summary':
				$this->view->zaction = 'class="active"';
				foreach((array)$dailys as $daily)
				{
					//计算本次项目金额总计
					$dailyTotal = 0;   //此次申请金额小计
					$temp_detail = @json_decode($daily['detail'],1);
					$loop_i = 0;
					foreach ((array)$temp_detail as $key=>$val) 
					{
						$itemTotal = 0;   //本次项目阶段金额小计
						$loop_i2   = 0;
						foreach((array)$val as $inkey =>$invalue)
						{
							if ('subtotal' == substr($inkey,-8)) 
							{  
								$dailyTotal =  floatval($dailyTotal) + floatval($invalue);
								$itemTotal = floatval($itemTotal) + floatval($invalue);
							}
						}
						$loop_i2++;
					}
					$daily["total"] = $dailyTotal;
					if(!array_key_exists($daily['nickname'],$result))
					{
						$result[$daily['nickname']] = array(); 
					}
					$result[$daily['nickname']][$daily['dateline']] = $daily;
					//计算总金额
					$result[$daily['nickname']]["total"] = floatval($result[$daily['nickname']]["total"]) + floatval($daily["total"]);
				}
				$this->view->sel_UName = $sel_UName;
			break;
			case 'mingxi':
				$this->view->maction = 'class="active"';
				foreach((array)$dailys as $daily)
				{
					//计算本次项目金额总计
					$dailyTotal = 0;   //此次申请金额小计
					$temp_detail = @json_decode($daily['detail'],1);
					$loop_i = 0;
					$daily["items"] = array();
					foreach ((array)$temp_detail as $key=>$val) 
					{
						$itemTotal = 0;   //本次项目阶段金额小计
						$loop_i2   = 0;
						foreach((array)$val as $inkey =>$invalue)
						{
							if ('subtotal' == substr($inkey,-8)) 
							{  
								$daily["items"][$key]['project_phase'] = $val['project_phase'];
								$daily["items"][$key][$inkey] = htmlspecialchars($invalue);
								$dailyTotal =  floatval($dailyTotal) + floatval($invalue);
								$itemTotal = floatval($itemTotal) + floatval($invalue);
							}
						}
						$daily["items"][$key]["total"] = htmlspecialchars($itemTotal);
						$loop_i2++;
					}
					$daily["total"] = $dailyTotal;
					
					if(!array_key_exists($daily['nickname'],$result))
					{
						$result[$daily['nickname']] = array(); 
					}
					$result[$daily['nickname']][$daily['dateline']] = $daily;
					
					//计算总金额
					$result[$daily['nickname']]["total"] = floatval($result[$daily['nickname']]["total"]) + floatval($daily["total"]);
				}
				$this->view->sel_UName = $sel_UName;
			break;
			case 'kehu':
				$this->view->kaction = 'class="active"';
				foreach((array)$dailys as $daily)
				{
					$temp_detail = @json_decode($daily['detail'],1);
					foreach ((array)$temp_detail as $key=>$val) 
					{
						$val['username'] = $daily['nickname'];
						if($customer && $val['work_object']!=$customer)
						{
							continue;
						}
						$result[$val['work_object']][$daily['dateline']][] = $val;
					}
				}
				$this->view->customer = $customer;
			break;
			case 'yuangong':
				$this->view->yaction = 'class="active"';
				foreach((array)$dailys as $daily)
				{
					$temp_detail = @json_decode($daily['detail'],1);
					$allTotal = 0;
					foreach ((array)$temp_detail as $key=>$val) 
					{
						$thisTotal = 0;
						foreach((array)$val as $inkey =>$invalue)
						{
							if ('subtotal' == substr($inkey,-8)) 
							{  
								$thisTotal  =  floatval($thisTotal)  + floatval($invalue);
								$allTotal   =  floatval($allTotal)   + floatval($invalue);
							}
						}
						$val['thistotal'] = $thisTotal;
						$result[$daily['nickname']][$daily['dateline']][$val['work_object']]['total'] += $thisTotal;
						$result[$daily['nickname']][$daily['dateline']][$val['work_object']]['times'] += 1;
						$result[$daily['nickname']][$daily['dateline']][$val['work_object']]['items'][] = $val;
					}
				}
				$this->view->sel_UName = $sel_UName;
			break;
			case 'huafei':
				$this->view->haction = 'class="active"';
				foreach((array)$dailys as $daily)
				{
					$temp_detail = @json_decode($daily['detail'],1);
					foreach ((array)$temp_detail as $key=>$val) 
					{
						if($customer && $val['work_object']!=$customer )
						{
							continue;
						}
						
						$thisTotal = 0;
						foreach((array)$val as $inkey =>$invalue)
						{
							if ('subtotal' == substr($inkey,-8)) 
							{  
								$thisTotal  =  floatval($thisTotal)  + floatval($invalue);
							}
						}
						$result[$val['work_object']]['items'][$daily['nickname']] += $thisTotal ;
						$result[$val['work_object']]['total']+= $thisTotal ;
					}
				}
				$this->view->customer = $customer;
			break;
		}
		$this->view->details = $details;
		$pw['project_phase'] = explode("\n",$_ENV['config']['project_phase']);
		$this->view->project_phase = $pw['project_phase'];
		$this->view->result = $result;
		$this->view->opt = $opt;
		$this->showMainPage('admincp/daily/daily_morereport');
	}

	/*[获得日报列表]*/
	private function GetDailys()
	{
		$where = " 1 ";
		if($_GET['start_date'] && $_GET['end_date'])
		{  // 开始和结束时间
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		if($_GET['searchUser'])
		{  // 用户
			$sel_UID = $_ENV['db']->fetchCol("SELECT m.uid FROM `admincp_member` as m where username='". $_GET['searchUser']."'");
        	$where .= ' and `uid` = '.$sel_UID;
		}
		$dailys = $_ENV['db']->fetchAll("SELECT * FROM `daily` WHERE {$where} order by created_time asc,daily_id desc");
		return $dailys;
	}
}